package com.hmdp.utils;

import com.hmdp.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获得 session
        HttpSession session = request.getSession();

        //判断用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.setStatus(401); //没有登录 返回401
            return false;
        }
        //将用户信息保存到threadLocal中去
        UserThreadLocal.saveUser(user);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户 避免内存泄露
        UserThreadLocal.removeUser();
    }
}
